package com.chinafree.business.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinafree.auth.model.bo.LoginUserBo;
import com.chinafree.auth.model.result.LoginResult;
import com.chinafree.auth.service.LoginUserService;
import com.chinafree.auth.service.NormalLoginService;
import com.chinafree.business.mapping.UserMapping;
import com.chinafree.business.model.param.BaseUserParam;
import com.chinafree.business.model.param.FilesUserParam;
import com.chinafree.business.model.param.ResumeUserParam;
import com.chinafree.business.model.queryCondition.UserQueryCondition;
import com.chinafree.business.model.result.BaseUserResult;
import com.chinafree.business.model.result.UserBaseMessageResult;
import com.chinafree.business.service.ResumeService;
import com.chinafree.business.service.UserService;
import com.chinafree.common.model.enumeration.ResponseCodeEnum;
import com.chinafree.common.model.response.BaseResponse;
import com.chinafree.common.model.response.EntityResponse;
import com.chinafree.common.model.response.ListPagingResponse;
import com.chinafree.mapper.UserRoleMapper;
import com.chinafree.model.po.*;
import com.chinafree.permission.model.po.UserRolePO;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class ResumeServiceImpl extends BaseServiceImpl implements ResumeService {

    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private NormalLoginService normalLoginService;

    @Autowired
    private LoginUserService loginUserService;

    public EntityResponse<LoginResult> updateUserCompany(String token) {
        MaUser maUser = new MaUser();
        maUser.setId(getUserId());
        maUser.setCompanyId(getCompanyId(token));
        userService.update(maUser);
        EntityResponse<LoginResult> login = normalLoginService.getLoginByUserId(getUserId());
        return login;
    }

    @Override
    public List<BaseUserResult> getHRsByCompanyIds() {
        MaUser maUser = new MaUser();
        maUser.setCompanyId(getCompanyId());
        Optional<List<MaUser>> option = userService.selectByUser(maUser);
        if (option.isPresent()) {
            List<BaseUserResult> list = UserMapping.instance.maUserToBaseUserResults(option.get());
            return list;
        }
        ;
        return null;
    }

    @Override
    public BaseResponse updateBaseUser(BaseUserParam body) {
        // 1.validateProcess
        validateProcess(body);
        MaUser maUser = UserMapping.instance.BaseUserParamToMaUser(body);
        maUser.setId(getUserId());
        userService.update(maUser);
        // 更新了这个相当于roleId=1
        if (loginUserService.getRoleIds(1, getUserId()) == null) {
            UserRolePO build = UserRolePO.builder().roleId(1).userId(getUserId()).build();
            userRoleMapper.insert(build);
        }
        return BaseResponse.success();
    }

    private void validateProcess(BaseUserParam body) {
        List<String> msg = new ArrayList<>();
    }

    @Override
    public EntityResponse<UserBaseMessageResult> getByUserId(Long userId) {
        UserBaseMessageResult userBaseMessageResult = new UserBaseMessageResult();
        // 1.获得user
        Optional<MaUser> maUserByUserId = userService.getMaUserByUserId(userId);
        if (!maUserByUserId.isPresent()) {
            return EntityResponse.failure("用户不存在");
        }
        MaUser maUser = maUserByUserId.get();
        userBaseMessageResult.setBaseUserResult(getBaseUserResult(maUser));
        extracted(userId, userBaseMessageResult);
        return new EntityResponse<>(ResponseCodeEnum.SUCCESS, "查询成功", userBaseMessageResult);
    }

    private void extracted(Long userId, UserBaseMessageResult userBaseMessageResult) {
        // 2.获得工作经验
        Optional<List<MaUserWork>> maUserWorksByUserId = userService.getMaUserWorksByUserId(userId);
        maUserWorksByUserId.ifPresent(maUserWorks -> userBaseMessageResult
                .setUserWorkResult(UserMapping.instance.maWorkToUserWorkResult(maUserWorks)));

        // 3.获得教育历程
        Optional<List<MaUserEducation>> maUserEducationsByUserId = userService.getMaUserEducationsByUserId(userId);
        maUserEducationsByUserId.ifPresent(maUserEducations -> userBaseMessageResult
                .setUserEducationResult(UserMapping.instance.maEducationToUserEducationResult(maUserEducations)));

        // 4.获得skills
        Optional<List<MaUserSkill>> maUserSkillsByUserId = userService.getMaUserSkillsByUserId(userId);
        maUserSkillsByUserId.ifPresent(maUserSkills -> userBaseMessageResult
                .setUserSkillResult(UserMapping.instance.maSkillToUserSkillResult(maUserSkills)));

        // 5.获得files
        Optional<List<MaUserFile>> maUserFileByUserId = userService.getMaUserFileByUserId(userId);
        maUserFileByUserId.ifPresent(maUserFileList -> userBaseMessageResult
                .setUserFileResult(UserMapping.instance.maFileToUserFileResult(maUserFileList)));
    }

    private BaseUserResult getBaseUserResult(MaUser maUser) {
        BaseUserResult baseUserResult = UserMapping.instance.maUserToBaseUserResult(maUser);
        baseUserResult.setLiveCityName(userService.getCityNameById(maUser.getLiveCity()));
        Integer liveCity = maUser.getLiveCity();
        baseUserResult.setLiveCityArray(getCityList(liveCity));
        FndPosition jobTypeById = userService.getJobTypeById(maUser.getJobType());
        if (jobTypeById != null) {
            baseUserResult.setJobTypeName(jobTypeById.getPositionName());
            baseUserResult.setJobTypeArray(Lists.newArrayList(jobTypeById.getType(), maUser.getJobType()));
        }
        if (baseUserResult.getBorn() != null) {
            long age = baseUserResult.getBorn().until(LocalDateTime.now(), ChronoUnit.YEARS);
            baseUserResult.setAge(String.valueOf(age));
        }
        return baseUserResult;
    }

    private ArrayList<String> getCityList(Integer liveCity) {
        ArrayList<String> list = new ArrayList<>();
        if (liveCity == null) {
            return null;
        }
        if (liveCity < 100) {
            list.add(liveCity.toString());
        } else {
            Integer liveCity1 = liveCity / 100;
            list.add(liveCity1.toString());
            list.add(liveCity.toString());
        }
        return list;
    }

    // public EntityResponse<BaseUserResult> getUserBaseInfoById(Long userId) {
    // Optional<MaUser> maUserByUserId = userService.getMaUserByUserId(userId);
    // if (!maUserByUserId.isPresent()) {
    // return EntityResponse.failure("用户不存在");
    // }
    // MaUser maUser = maUserByUserId.get();
    // BaseUserResult baseUserResult =
    // UserMapping.instance.maUserToBaseUserResult(maUser);
    // baseUserResult.setLiveCityName(commonService.getCityNameById(maUser.getLiveCity()));
    // baseUserResult.setJobTypeName(commonService.getJobTypeById(maUser.getJobType()));
    // return new EntityResponse<>(ResponseCodeEnum.SUCCESS, "查询成功",
    // baseUserResult);
    // }
    //
    //
    // public EntityResponse<UserResumeResult> getUserResumeById(Long userId) {
    // UserResumeResult userBaseMessageResult = new UserResumeResult();
    // //1.获得user
    // Optional<MaUser> maUserByUserId = userService.getMaUserByUserId(userId);
    // if (!maUserByUserId.isPresent()) {
    // return EntityResponse.failure("用户不存在");
    // }
    // userBaseMessageResult.setSummary(maUserByUserId.get().getSummary());
    //
    // //2.获得工作经验
    // Optional<List<MaUserWork>> maUserWorksByUserId =
    // userService.getMaUserWorksByUserId(userId);
    // maUserWorksByUserId.ifPresent(maUserWorks ->
    // userBaseMessageResult.setUserWorkResult(UserMapping.instance.maWorkToUserWorkResult(maUserWorks)));
    //
    // //3.获得教育历程
    // Optional<List<MaUserEducation>> maUserEducationsByUserId =
    // userService.getMaUserEducationsByUserId(userId);
    // maUserEducationsByUserId.ifPresent(maUserEducations ->
    // userBaseMessageResult.setUserEducationResult(UserMapping.instance.maEducationToUserEducationResult(maUserEducations)));
    //
    // //4.获得skills
    // Optional<List<MaUserSkill>> maUserSkillsByUserId =
    // userService.getMaUserSkillsByUserId(userId);
// maUserSkillsByUserId.ifPresent(maUserSkills ->
// userBaseMessageResult.setUserSkillResult(UserMapping.instance.maSkillToUserSkillResult(maUserSkills)));
//
// return new EntityResponse<>(ResponseCodeEnum.SUCCESS, "查询成功",
// userBaseMessageResult);
// }
//
// public BaseResponse insertBaseUser(BaseUserParam body) {
// //1.validateProcess
// validateProcess(body);
// MaUser maUser = UserMapping.instance.BaseUserParamToMaUser(body);
// userService.insert(maUser);
// return BaseResponse.success();
// }    @Override
@Transactional
public BaseResponse updateResumeUser(ResumeUserParam body) {
    validateProcess(body);
    Long id = getUserId();
    MaUser build = MaUser.builder().summary(body.getSummary()).build();
    build.setId(id);
    userService.update(build);
    if (CollectionUtils.isNotEmpty(body.getUserEducationParams())) {
        List<MaUserEducation> maUserEducations = UserMapping.instance
                .UserEducationParamsToEntities(body.getUserEducationParams(), id);
        userService.updateMaUserEducation(maUserEducations, id);
    }
    if (CollectionUtils.isNotEmpty(body.getUserWorkParams())) {
        final List<MaUserWork> maUserWorks = UserMapping.instance.UserWorkParamsToEntities(body.getUserWorkParams(),
                id);
        userService.updateMaUserWork(maUserWorks, id);
    }
    if (CollectionUtils.isNotEmpty(body.getUserSkillParams())) {
        List<MaUserSkill> maUserSkills = UserMapping.instance.UserSkillParamsToEntities(body.getUserSkillParams(),
                id);
        userService.updateMaUserSkill(maUserSkills, id);
    }
    return BaseResponse.success();
}


    @Override
    public BaseResponse updateFileUser(List<FilesUserParam> body) {
        if (CollectionUtils.isNotEmpty(body)) {
            List<MaUserFile> maUserFile = UserMapping.instance.UserFileParamsToEntities(body);
            userService.updateMaUserFile(maUserFile);
        }
        return BaseResponse.success();
    }

    private void validateProcess(ResumeUserParam body) {
    }

    @Override
    public ListPagingResponse<UserBaseMessageResult> queryUserPage(UserQueryCondition userQueryCondition) {
        Page<MaUser> maUserPage = userService.selectUserListPage(userQueryCondition);
        List<BaseUserResult> baseUserResultList = maUserPage.getRecords().stream().map(this::getBaseUserResult)
                .collect(Collectors.toList());
        ArrayList<UserBaseMessageResult> list = new ArrayList<>();
        for (BaseUserResult b : baseUserResultList) {
            UserBaseMessageResult result = new UserBaseMessageResult();
            result.setBaseUserResult(b);
            extracted(b.getId(), result);
            list.add(result);
        }
        return new ListPagingResponse<>(ResponseCodeEnum.SUCCESS, "查询成功", list, maUserPage.getCurrent(),
                maUserPage.getRecords().size(), maUserPage.getTotal());
    }

    @Override
    public BaseResponse updateResumeStatus(Byte status) {
        MaUser build = MaUser.builder().enableResume(status).build();
        build.setId(getUserId());
        userService.update(build);
        return BaseResponse.success();
    }

}